package com.tobeface.wechat.message.handler;

import com.google.common.base.Stopwatch;
import com.tobeface.wechat.message.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author loudyn
 */
public abstract class WeChatMessageHandlerSupport implements WeChatMessageHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public final boolean isSupport(WeChatMessage message) {
        String msgType = (String) message.getPayloads().get(WeChatMessagePayloads.MSGTYPE_PAYLOAD);
        return isMessageTypeSupport(msgType, message);
    }

    protected abstract boolean isMessageTypeSupport(String msgType, WeChatMessage message);

    @Override
    public final void messageReceived(WeChatMessageContext context, WeChatMessage message) {
        Stopwatch watch = new Stopwatch().start();
        try {

            onMessageReceived(context.getChannel(), message);
        } finally {
            afterMessageReceived(context, message, watch.stop().elapsed(TimeUnit.MILLISECONDS));
        }
    }

    /**
     * @param context
     * @param message
     * @param elapsed
     */
    protected void afterMessageReceived(WeChatMessageContext context, WeChatMessage message, long elapsed) {
        //add hook
    }

    /**
     * @param channel
     * @param message
     */
    protected abstract void onMessageReceived(WeChatMessageChannel channel, WeChatMessage message);

    /**
     *
     * @return
     */
    protected final Logger getLogger() {
        return logger;
    }

    @Override
    public int getPriority() {
        return MEDIUM_PRIORITY;
    }

    @Override
    public final int compareTo(WeChatMessageHandler other) {
        return other.getPriority() - getPriority();
    }
}
